<template>
  <div class="app-container">

    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="资产名称" prop="assetName">
        <el-input v-model="queryParams.assetName" placeholder="请输入资产名称" clearable size="mini"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="负责人" prop="adminNickName">
        <el-input v-model="queryParams.adminNickName" placeholder="请输入负责人" clearable size="mini"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="设备编码" prop="deviceNum">
        <el-input v-model="queryParams.deviceNum" placeholder="请输入设备编码" clearable size="mini"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="固定资产" name="0"/>
      <el-tab-pane label="移动资产" name="1"/>
    </el-tabs>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['module:asset:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['module:asset:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-download" size="mini" :loading="exportLoading" @click="handleImportWyf"
                   v-hasPermi="['module:asset:import']">导入资产列表
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="assetList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="所属小区" align="center" prop="deviceEstateName"/>
<!--      <el-table-column label="资产名称" align="center" prop="assetName"/>-->
      <el-table-column label="资产名称" align="center" width="150" v-if="activeName == 0">
        <template slot-scope="scope">
          <el-popover placement="right" width="400" trigger="hover">
            <el-image style="width: 380px; height: 380px" :src="'https://www.caihengyun.com/chyimg/'+scope.row.qrCode" fit="fill"/>
            <i class="el-icon-picture" slot="reference"/>
          </el-popover>
          <el-button size="mini" type="text" icon="el-icon-download"
                     @click="downloadGudingImg(scope.row)">{{ scope.row.assetName }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="资产名称" align="center" width="150"  v-if="activeName == 1">
        <template slot-scope="scope">
          <el-popover placement="right" width="400" trigger="hover">
            <el-image style="width: 380px; height: 380px" :src="'https://www.caihengyun.com/chyimg/'+scope.row.qrCode" fit="fill"/>
            <i class="el-icon-picture" slot="reference"/>
          </el-popover>
          <el-button size="mini" type="text" icon="el-icon-download"
                     @click="downloadYidongImg(scope.row)">{{ scope.row.assetName }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="资产类型" align="center" prop="assetType">
        <template slot-scope="scope">
          <div>
            <el-tag v-if="scope.row.assetType === 0" style="cursor: pointer" :type="''">固定资产</el-tag>
            <el-tag v-if="scope.row.assetType === 1" style="cursor: pointer" :type="'info'">移动资产</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="资产状态" align="center" prop="state">
        <template slot-scope="scope">
          <div>
            <el-tag v-if="scope.row.state === 0" style="cursor: pointer" :type="'success'">正常</el-tag>
            <el-tag v-if="scope.row.state === 1" style="cursor: pointer" :type="'warning'">维修</el-tag>
            <el-tag v-if="scope.row.state === 2" style="cursor: pointer" :type="'danger'">报废</el-tag>
            <el-tag v-if="scope.row.state === 3" style="cursor: pointer" :type="'info'">借出</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="设备类型" align="center" prop="deviceType">
        <template slot-scope="scope">
          <div>
            <el-tag v-if="scope.row.deviceType === 0" style="cursor: pointer" :type="'success'">办公用品</el-tag>
            <el-tag v-if="scope.row.deviceType === 1" style="cursor: pointer" :type="'warning'">消防安防设备</el-tag>
            <el-tag v-if="scope.row.deviceType === 2" style="cursor: pointer" :type="'danger'">交通运输设备</el-tag>
            <el-tag v-if="scope.row.deviceType === 3" style="cursor: pointer" :type="'info'">大型工具设备</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="设备编码" align="center" prop="deviceNum"/>

      <!--      <el-table-column label="折旧时间" align="center" prop="depreciationTime" width="180">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{ parseTime(scope.row.depreciationTime, '{y}-{m}-{d}') }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="采购时间" align="center" prop="procureTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.procureTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="盘点时间" align="center" prop="lastCheckTime" v-if="activeName==0">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastCheckTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="盘点状态" align="center" prop="lastCheckState" width="180" v-if="activeName==0">
        <template slot-scope="scope">
          <div>
            <el-tag v-if="scope.row.lastCheckState === 0" style="cursor: pointer" :type="'success'">正常</el-tag>
            <el-tag v-if="scope.row.lastCheckState === 1" style="cursor: pointer" :type="'warning'">维修</el-tag>
            <el-tag v-if="scope.row.lastCheckState === 2" style="cursor: pointer" :type="'danger'">报废</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="折旧率" align="center" prop="depreciation">
        <template slot-scope="scope">
          {{scope.row.depreciation+"%"}}
        </template>
      </el-table-column>
      <el-table-column label="购置金额" align="center" prop="procureMoney"/>
      <el-table-column label="负责人" align="center" prop="adminNickName"/>
      <el-table-column label="备注" align="center" prop="remake"/>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180px">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-picture" @click="resetGudingCord(scope.row)"
                     v-if="activeName==0">生成二维码
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-picture" @click="resetYidongCord(scope.row)"
                     v-if="activeName==1">生成二维码
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-s-goods" v-if="activeName==0">
            <router-link :to="'/asset/checkRecord?assetId=' + scope.row.id" class="link-type">
              盘点记录
            </router-link>
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-s-goods" v-if="activeName==1">
            <router-link :to="'/asset/borrowRecord?assetId=' + scope.row.id" class="link-type">
              借取记录
            </router-link>
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['module:asset:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['module:asset:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"/>



    <!-- 设备导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgressAsset"
        :on-success="handleFileAssetSuccess"
        :auto-upload="false"
        drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--          <div class="el-upload__tip" slot="tip">-->
          <!--            <el-checkbox v-model="uploadWyfYear.updateSupport" /> 是否更新已经存在的用户数据-->
          <!--          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplateAsset">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="submitFileFormAsset">确 定</el-button>
        <el-button @click="upload.open = false" size="mini">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改资产管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="640px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="所在小区" prop="estateId">
              <el-select v-model="form.estateId" placeholder="请选择小区" size="mini" style="width:100%;" filterable
                         clearable>
                <el-option v-for="estate in estatesOptions"
                           :key="estate.id"
                           :label="estate.estateName"
                           :value="estate.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产类型" prop="assetType">
              <el-radio-group v-model="form.assetType" size="mini" style="width: 100%">
                <el-radio :value="0" :label="0">固定资产</el-radio>
                <el-radio :value="1" :label="1">移动资产</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="设备类型" prop="deviceType">
              <el-radio-group v-model="form.deviceType" size="mini" style="width: 100%">
                <el-radio :value="0" :label="0">办公用品</el-radio>
                <el-radio :value="1" :label="1">消防安防设备</el-radio>
                <el-radio :value="2" :label="2">交通运输设备</el-radio>
                <el-radio :value="3" :label="3">大型工具设备</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="资产名称" prop="assetName">
              <el-input v-model="form.assetName" placeholder="请输入资产名称" size="mini"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人员" prop="adminNickName">
              <el-input v-model="form.adminNickName" placeholder="请输入负责人" size="mini"/>
            </el-form-item>
          </el-col>
        </el-row>
       <el-row>
         <el-col :span="12">
           <el-form-item label="采购时间" prop="procureTime">
             <el-date-picker clearable size="mini" v-model="form.procureTime" type="datetime"
                             value-format="yyyy-MM-dd HH:mm:ss"
                             placeholder="选择采购时间">
             </el-date-picker>
           </el-form-item>
         </el-col>
         <el-col :span="12">
           <el-form-item label="折旧时间" prop="depreciationTime">
             <el-date-picker clearable size="mini" v-model="form.depreciationTime" type="datetime"
                             value-format="yyyy-MM-dd HH:mm:ss"
                             placeholder="选择折旧时间">
             </el-date-picker>
           </el-form-item>
         </el-col>
       </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="购置金额" prop="procureMoney">
              <el-input v-model="form.procureMoney" placeholder="请输入购置金额" size="mini"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备备注" prop="remake">
              <el-input v-model="form.remake" placeholder="请输入备注" size="mini"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="资产位置" prop="procureMoney">
              <el-input v-model="form.assetPosition" placeholder="请输入资产位置" size="mini"/>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel" size="mini">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listAsset, getAsset, delAsset, addAsset, updateAsset, exportAsset, resetYidongCord,resetGudingCode} from "@/api/module/asset/asset";
import {listAllEstate} from "@/api/module/estate/estate";
import Template from "@/views/module/wx/template.vue";
import {getToken} from "@/utils/auth";

export default {
  name: "Asset",
  components: {Template},
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资产管理表格数据
      assetList: [],
      activeName: "0",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        assetType: 0,
      },
      estatesOptions: [],
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "资产数据导入",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/module/asset/import"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        estateId: [
          {
            required: true, message: "所属小区不能为空", trigger: "change"
          }
        ],
        assetName: [
          {
            required: true, message: "资产名称不能为空", trigger: "blur"
          }
        ],
        assetType: [
          {
            required: true, message: "资产类型不能为空", trigger: "blur"
          }
        ],
        adminNickName: [
          {
            required: true, message: "负责人不能为空", trigger: "blur"
          }
        ],
        // depreciationTime: [
        //   {
        //     required: true, message: "折旧时间不能为空", trigger: "blur"
        //   }
        // ],
        // procureTime: [
        //   {
        //     required: true, message: "采购时间不能为空", trigger: "blur"
        //   }
        // ],
        procureMoney: [
          {
            required: true, message: "购置金额不能为空", trigger: "blur"
          }
        ],
        state: [
          {
            required: true, message: "资产状态不能为空", trigger: "blur"
          }
        ],
        deviceType: [
          {
            required: true,
            message: "设备类型不能为空",
            trigger: "blur"
          }
        ],
      }
    }
  },
  created() {
    this.getList();
    this.getEstateList();
  },
  methods: {
    /** 查询资产管理列表 */
    getList() {
      this.loading = true;
      listAsset(this.queryParams).then(response => {
        this.assetList = response.rows;
        this.total = response.total;
        this.loading = false;
        console.log(this.assetList);
      });
    },
    handleImportWyf() {
      this.upload.title = "资产数据导入";
      this.upload.open = true;
    },
    resetGudingCord(row) {
      var data = {
        id: row.id
      };
      resetGudingCode(data).then(response => {
        if (response.code === 200) {
          this.msgSuccess("生成成功");
          this.getList();
        } else {
          this.msgError("生成失败");
        }
      });
    },
    resetYidongCord(row) {
      var data = {
        id: row.id
      };
      resetYidongCord(data).then(response => {
        if (response.code === 200) {
          this.msgSuccess("生成成功");
          this.getList();
        } else {
          this.msgError("生成失败");
        }
      });
    },
    downloadGudingImg(row) {
      window.location.href = process.env.VUE_APP_BASE_API + "/common/download/gudingAsset/" + row.id;
    },
    downloadYidongImg(row) {
      window.location.href = process.env.VUE_APP_BASE_API + "/common/download/yidongAsset/" + row.id;
    },
    // 文件上传中处理
    handleFileUploadProgressAsset(event, file, fileList) {
      this.uploadWyfYear.isUploading = true;
    },
    /** 下载模板操作 */
    importTemplateAsset() {
      window.location.href = "https://www.caihengyun.com/chyimg/file/temp/%E8%B5%84%E4%BA%A7%E7%B1%BB%E7%9B%AE%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx";
    },
    submitFileFormAsset() {
      this.$refs.upload.submit();
    },
    // 文件上传成功处理
    handleFileAssetSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    handleClick(val) {
      console.log('handleClick', val.name);
      this.activeName = val.name;
      this.queryParams.assetType = parseInt(val.name);
      this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    getEstateList() {
      listAllEstate().then(response => {
        this.estatesOptions = response.data;
      });
    },

    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        estateId: undefined,
        assetName: undefined,
        assetType: 0,
        adminNickName: undefined,
        depreciationTime: undefined,
        procureTime: undefined,
        procureMoney: undefined,
        state: 0,
        deviceType: 0,
        deviceNum: undefined,
        remake: undefined,
        assetPosition:undefined,
      }
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加资产管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids;
      getAsset(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改资产管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateAsset(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addAsset(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除资产管理编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.loading = true;
        return delAsset(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有资产管理数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportAsset(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    }
  }
};
</script>
